/**
 * 
 */
package com.gooex.web.action.manage.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.c4j.system.web.action.Protected;
import org.c4j.system.web.exception.ServiceException;

import com.gooex.domain.base.Order;
import com.gooex.domain.base.OrderCustomer;
import com.gooex.domain.base.OrderRequest;
import com.gooex.domain.base.OrderVendor;
import com.gooex.domain.base.Product;
import com.gooex.domain.base.Property;
import com.gooex.domain.base.PropertyValue;
import com.gooex.domain.base.emun.OrderStatus;
import com.gooex.domain.organization.Address;
import com.gooex.domain.organization.User;
import com.gooex.service.base.IProductManager;
import com.gooex.service.base.exception.ExceptionCode;
import com.gooex.service.organization.IAddressManager;
import com.opensymphony.xwork2.Action;

/**
 * @author Adonis
 */
@SuppressWarnings("unchecked")
public class ManageOrderAction extends BaseOrderAction implements Protected {

	private static final long serialVersionUID = 7177472566823381202L;

	private IProductManager productManager;

	private IAddressManager addressManager;

	private String id;

	private String productId;

	private Date deadline;

	private Order order;

	private Product product;

	private Address selectAddress;

	private OrderRequest orderRequest;

	private List<Address> addresses;

	private List propertyValues;

	private List<Property> properties;

	private List<Order> orders;

	/**
	 * 到增加页面之前需要做的操作
	 */
	public String preAdd() {
		if (StringUtils.isBlank(id)) {
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
		}

		this.product = productManager.getProduct(id);
		if (this.product == null) {
			throw new ServiceException(ExceptionCode.PRODUCT_NOT_EXISTS, "");
		}

		return SUCCESS;
	}

	/**
	 * 增加订单
	 * 
	 * @return
	 */
	public String add() {
		if (order == null || !order.validate()) {
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
		}

		// 设置状态
		order.setStatus(OrderStatus.INVITING);
		// 设置创建时间
		order.setCreationTime(new Date());

		// 设置创建人
		User user = getCurrentUser();
		if (user == null) {
			throw new ServiceException(ExceptionCode.USER_NOT_EXISTS, "");
		}
		order.setCreateUser(user);
		order.setResponsibleUser(user);

		orderManager.createOrder(order);

		return SUCCESS;
	}

	public String getAll() throws Exception {
		orders = orderManager.getOrders(page);
		return SUCCESS;
	}

	public String getCreateOrders() throws Exception {
		orders = orderManager.getOwnCreateOrder(getCurrentUser().getId(), page);
		return Action.SUCCESS;
	}

	public String getParticepateOrders() throws Exception {
		orders = orderManager.getParticipateOrder(getCurrentUser().getId(), page);
		return Action.SUCCESS;
	}

	/**
	 * 将订单状态手动从已保存状态修改为邀请状态
	 * 
	 * @return
	 * @throws Exception
	 */
	public String changeStatus() throws Exception {
		Order order = getOrder(id);

		// 只能是创建者才能修改为邀请状态
		/**
		 * (TODO 可考虑支持超级管理员修改)
		 */
		String userName = getCurrentUser().getName();
		if (!userName.equals(order.getCreateUser().getName())) {
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
		}

		// 只能手动修改已保存状态的订单状态
		if (!OrderStatus.SAVED.equals(order.getStatus())) {
			throw new ServiceException(ExceptionCode.ORDER_STATUS_NOT_SAVED, "");
		}

		// 设置定单状态为邀请状态
		order.setStatus(OrderStatus.INVITING);

		orderManager.saveOrder(order);

		return userCenterSuccessPage("order/listOwnCreateOrders.do", "订单已成功进入邀请状态");
	}

	public String delStatus() throws Exception {
		Order order = getOrder(id);

		// 如果用户是创建者和管理员才能够支持取消此订单
		User user = getCurrentUser();
		if (!user.isSystemUser()) {
			if (!user.getName().equals(order.getCreateUser().getName())) {
				throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
			}

			if (order.getStatus().equals(OrderStatus.CANCELED)) {
				throw new ServiceException(ExceptionCode.ORDER_HAS_CANCELED, "");
			}
		}

		// 设置定单状态为邀请状态
		order.setStatus(OrderStatus.CANCELED);

		orderManager.saveOrder(order);

		return SUCCESS;
	}

	public String delete() throws Exception {
		Order order = getOrder(id);

		// 只能是创建者才能删除订单
		User user = getCurrentUser();
		if (!user.isSystemUser()) {
			if (!user.getName().equals(order.getResponsibleUser().getName())) {
				throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
			}
			// 只能删除已保存状态的订单
			if (!OrderStatus.SAVED.equals(order.getStatus())) {
				throw new ServiceException(ExceptionCode.ORDER_STATUS_NOT_SAVED, "");
			}
		}
		orderManager.removeOrder(order);

		return SUCCESS;
	}

	public String preEdit() throws Exception {
		this.order = getOrder(id);

		// 只能是创建者才能编辑订单
		/**
		 * (TODO 可考虑支持超级管理员编辑)
		 */
		String userName = getCurrentUser().getName();
		if (!userName.equals(order.getCreateUser().getName())) {
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");

		}

		this.properties = propertyManager.getProperties();

		propertyValues = new ArrayList<PropertyValue>();
		for (Property item : this.properties) {
			for (PropertyValue i : item.getValues()) {
				propertyValues.add(i);
			}
		}

		return Action.SUCCESS;
	}

	public String edit() throws Exception {
		Order oldOrder = getOrder(this.order.getId());

		// 只能是创建者才能编辑订单
		/**
		 * (TODO 可考虑支持超级管理员编辑)
		 */
		String userName = getCurrentUser().getName();
		if (!userName.equals(oldOrder.getCreateUser().getName())) {
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
		}

		if (order == null || StringUtils.isBlank(order.getTitle())
				|| order.getMinCustomerNum() > order.getMaxCustomerNum()
				|| order.getMinVendorNum() > order.getMaxVendorNum()) {
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
		}

		oldOrder.setTitle(order.getTitle());
		oldOrder.setMinCustomerNum(order.getMinCustomerNum());
		oldOrder.setMinVendorNum(order.getMinVendorNum());
		oldOrder.setMaxCustomerNum(order.getMaxCustomerNum());
		oldOrder.setMaxVendorNum(order.getMaxVendorNum());

		orderManager.updateOrder(oldOrder);

		return userCenterSuccessPage("order/listOwnCreateOrders.do", "成功更新订单");
	}

	public String preTakePartInOrder() throws Exception {
		order = getOrder(order.getId());

		// 订单不处于确认、关闭、取消状态
		if (order.isCanceled() || order.isClosed() || order.isConfirmed()) {
			throw new ServiceException(ExceptionCode.NOT_INVITING_ORDER, "");
		}

		product = productManager.getProduct(productId);
		if (product == null) {
			throw new ServiceException(ExceptionCode.SYSTEM_ACCESS_ERROR, "");
		}

		// 获取用户所有的地址簿
		this.addresses = addressManager.getUserAddresses(getCurrentUser());
		OrderCustomer customer = orderManager.getOrderCustomer(order, getCurrentUser());
		// 获取用户之前创建的订单请求的地址
		this.selectAddress = customer == null ? null : customer.getAddress();

		return SUCCESS;
	}

	public String takePartIn() throws Exception {
		validateTakePartIn();
		orderRequest.getOrderCustomer().setUser(super.getCurrentUser());
		orderManager.saveOrderRequest(orderRequest);

		order = orderRequest.getOrderCustomer().getOrder();

		if (orderRequest.getOrderCustomer().getAddress() == null) {
			return "address";
		}

		return userCenterSuccessPage("order/listTakePartInOrders.do", "成功加入订单");
	}

	private Order getOrder(String orderId) {
		Order oldOrder = orderManager.getOrder(orderId);

		// 订单不存在
		if (oldOrder == null) {
			throw new ServiceException(ExceptionCode.ORDER_NOT_EXISTS, "");
		}

		return oldOrder;
	}

	/**
	 * 不管后台验证了，都看作是非法操作
	 * 
	 * @throws Exception
	 */
	private void validateTakePartIn() throws Exception {
		if (this.orderRequest == null) {
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
		}
		OrderCustomer orderCustomer = orderRequest.getOrderCustomer();

		if (orderCustomer == null || this.orderRequest.getCount() <= 0 || orderCustomer.getOrder() == null
				|| StringUtils.isBlank(orderCustomer.getOrder().getId())) {
			// 如果用户未对订单的商品的参数进行任何的选择，则视为随意，允许此种情况
			throw new ServiceException(ExceptionCode.OPERATION_NOT_ALLOWED, "");
		}

		this.orderRequest.setPropertyValues(propertyValues);

	}

	public String cancelOrderRequest() throws Exception {
		this.orderManager.cancelOrderRequest(id);
		return userCenterSuccessPage("order/listTakePartInOrders.do", "成功取消订单请求");
	}

	public String changeOrderStatus() throws Exception {
		Order order = orderManager.getOrder(id);
		if (order == null || !order.isOrderManager(getCurrentUser()))
			throw new ServiceException(ExceptionCode.SYSTEM_ACCESS_ERROR, "");

		if (deadline != null && deadline.after(new Date())) {
			order.setDeadline(deadline);
		}
		orderManager.changeOrderStatus(order);
		return userCenterSuccessPage("order/viewOrder.do?id=" + order.getId(), "成功改变订单状态");
	}

	/**
	 * 查看订单投票情况<br>
	 * 传入参数:id - 订单id<br/>
	 */
	public String viewOrderVote() throws Exception {
		order = orderManager.getOrder(id);
		if (order == null) {
			addActionError(ExceptionCode.ORDER_NOT_EXISTS);
			return ERROR;
		}
		if (!order.isVoting() || !isOrderCustomer(order)) {
			addActionError(ExceptionCode.SYSTEM_ACCESS_ERROR);
			return ERROR;
		}

		return SUCCESS;
	}

	/**
	 * 获取当前人对当前订单的订单请求
	 */
	public OrderCustomer getOrderCustomer() {
		if (getCurrentUser() == null || order == null)
			return null;
		return orderManager.getOrderCustomer(order, getCurrentUser());
	}

	/**
	 * 获取当前人对当前订单的订单供应信息
	 */
	public OrderVendor getOrderVendor() {
		if (getCurrentUser() == null || order == null)
			return null;
		return orderManager.getOrderVendor(order, getCurrentUser());
	}

	// /////////////////
	// // getter\setter
	// /////////////////

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public List getPropertyValues() {
		return propertyValues;
	}

	public void setPropertyValues(List propertyValues) {
		this.propertyValues = propertyValues;
	}

	public List<Property> getProperties() {
		return properties;
	}

	public List<Order> getOrders() {
		return orders;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setProductManager(IProductManager productManager) {
		this.productManager = productManager;
	}

	public Product getProduct() {
		return product;
	}

	public void setOrderRequest(OrderRequest orderRequest) {
		this.orderRequest = orderRequest;
	}

	public OrderRequest getOrderRequest() {
		return this.orderRequest;
	}

	public Date getDeadline() {
		return deadline;
	}

	public void setDeadline(Date deadline) {
		this.deadline = deadline;
	}

	public List<Address> getAddresses() {
		return addresses;
	}

	public Address getSelectAddress() {
		return selectAddress;
	}

	public void setAddressManager(IAddressManager addressManager) {
		this.addressManager = addressManager;
	}

	public void setSelectAddress(Address selectAddress) {
		this.selectAddress = selectAddress;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}
}
